package com.demo.controller;

import com.demo.entity.Account;
import com.demo.entity.Customer;
import com.demo.repository.AccountRepo;
import com.demo.repository.CustomerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/customers")
public class AccountController {

    @Autowired
    private CustomerRepo customerRepo;

    @Autowired
    private AccountRepo accountRepo;

    @PostMapping(value = "/{customerId}/accounts")
    @ResponseStatus(code = HttpStatus.CREATED)
    public Account save(@PathVariable Integer customerId, @RequestBody Account account) {
        return customerRepo.findById(customerId).map(customer -> {
            account.setCustomer(customer);
            return accountRepo.save(account);
        }).orElseThrow(() -> new RuntimeException(
                "Customer [customerId=" + customerId + "] can't be found"
        ));
    }

    @GetMapping("/{customerId}/accounts")
    public Page<Account> all(@PathVariable Integer customerId, Pageable pageable) {
        if (!customerRepo.existsById(customerId)) {
            throw new RuntimeException("Customer [customerId=" + customerId + "] can't be found");
        }
        return accountRepo.findByCustomerCustomerId(customerId, pageable);
    }

    @DeleteMapping("/{customerId}/accounts/{accountId}")
    public ResponseEntity<?> deleteAccount(@PathVariable Integer customerId, @PathVariable Integer accountId) {
        if (!customerRepo.existsById(customerId)) {
            throw new RuntimeException("Customer [customerId=" + customerId + "] can't be found");
        }
        return accountRepo.findById(accountId).map(account -> {
            accountRepo.delete(account);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new RuntimeException(
                "Account [accountId=" + accountId + "] can't be found"
        ));
    }

    @PutMapping("/{customerId}/accounts/{accountId}")
    public ResponseEntity<Account> updateAccount(@PathVariable Integer customerId, @PathVariable Integer accountId, @RequestBody Account newAccount) {
        Customer customer = customerRepo.findById(customerId).orElseThrow(() -> new RuntimeException(
                "Customer [customerId=" + customerId + "] can't be found"
        ));

        return accountRepo.findById(accountId).map(account -> {
            newAccount.setAccountId(accountId);
            newAccount.setCustomer(customer);
            accountRepo.save(newAccount);
            return ResponseEntity.ok(newAccount);
        }).orElseThrow(() -> new RuntimeException(
                "Account [accountId=" + accountId + "] can't be found"
        ));
    }
}
